<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="employeeQuery">
        <el-form-item>
          <el-input v-model="employeeQuery.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getemployees">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleImport">导入线索</el-button>
        </el-form-item>
        <el-form-item>
<!--          <a href="/employee/download">导出</a>-->
          <el-button type="primary" @click="exportSubmit">导出线索</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="username" label="登录名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="200" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="部门" width="120" sortable>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" size="small" @click="handleRole(scope.$index, scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="employeeQuery.currentPage"
          :page-sizes="[3, 5, 10, 20]"
          :page-size="employeeQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑/新增界面-->
    <el-dialog title="编辑/新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="editForm">
        <el-form-item label="登录名" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
<!--        <el-form-item label="头像" prop="headImage">-->
<!--          <el-input v-model="saveForm.headImage" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department.id">
          <el-select clearable v-model="saveForm.department" value-key="id" style="width: 100%" placeholder="请选择">
            <el-option
                v-for="item in departments"
                :key="item.value"
                :label="item.name"
                :value="item">
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--分配角色-->
    <el-dialog title="分配角色" :visible.sync="roleFormVisible" :close-on-click-modal="false">
      <el-form :model="roleForm" label-width="80px" ref="roleForm">
        <el-form-item label="登录名" prop="username">
          <el-input v-model="roleForm.username" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="department.id">
          <el-tree
              :data="roles"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="tree"
              highlight-current
              :props="defaultProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="roleSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--导入员工-->
    <el-dialog title="导入员工" :visible.sync="importFormVisible" :close-on-click-modal="false">
      <el-form label-width="180px" ref="roleForm">
        <el-form-item label="请选择要导入的文件" prop="file">
          <el-upload
              ref="upload"
              style="display: inline-block"
              :show-file-list="false"
              accept="xlsx"
              :on-success="handleExcelImportSuccess"
              class="upload-demo"
              name="file"
              :headers="header"
              :auto-upload="false"
              action="http://47.115.229.64:8081/employee/upload">
<!--            上线环境-->
<!--              action="/api/employee/upload">-->
            <!--开发环境-->
<!--            action="http://localhost:8080/employee/upload">-->
<!--            本地测试-->
<!--            action="http://api.cwf.com/employee/upload">-->
<!--            nginx代理-->
            <el-button type="primary">导入<i class="el-icon-bottom"></i></el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="importFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="importSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

export default {
  data() {
    return {
      // 分页信息
      pageInfo: {
        total: 0,
        list: []
      },
      // 高级查询
      employeeQuery: {
        keyword: null,
        currentPage: 1,
        pageSize: 10
      },

      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//编辑界面是否显示
      editLoading: false, // 编辑页面是否提交中
      importFormVisible:false,//导入界面是否显示
      saveFormRules: { // 表单验证规则
        username: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        username: '',
        email: '',
        headImage: '',
        age: '',
        department: {
          id: null,
          name: ''
        }
      },
      // 角色列表
      roles: [],
      roleFormVisible: false,// 分配角色界面是否显示
      roleForm: {
        id: null,// 用户id
        username: '',
        roles: []
      },
      // 权限默认配置
      defaultProps: {
        label: 'name'
      },
      // 获取部门列表
      departments: [],
      // 文件列表
      fileList:[],
      header:{
        "token":sessionStorage.getItem("token")
      }
    }
  },
  methods: {
    // 导出提交
    exportSubmit(){
      if (Object.is(this.employeeQuery.keyword, null)){
        this.employeeQuery.keyword = ""
      }
      if (this.pageInfo.list.length === 0){
        this.$message({
          message: "请选择要导出的员工！",
          type:'warning'
        });
        return;
      }
      this.$http.post("/employee/export",{keyword:this.employeeQuery.keyword}).then(result => {
        this.$message({
          message: "导出成功！",
          type:'success'
        });
      })
    },
    // 导入
    handleExcelImportSuccess(res){
      if(res.success){
        // 判断返回的失败数组
        if (res.data.length<=0){
          this.$message({
            message: "导入成功",
            type:'success'
          });
        }else{
          console.log("下面的数据有问题,请修改本条数据，重新导入")
          console.log(res.data);
          const msg  = res.data.map(item => {
            return item.username + " " + item.email + " " + item.age + " " + item.department.name;
          }).join("<br/>");
          const h = this.$createElement;

          this.$notify({
            title: '下面的数据有问题,请修改本条数据，重新导入',
            message: h('i', { style: 'color: teal'}, msg)
          });
        }
        this.importFormVisible = false;
        this.getemployees();
      }else{
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    handleImport(){
      this.importFormVisible = true;
    },
    importSubmit(){
      try {
        this.$refs.upload.submit();
      }catch (e) {
        this.$message({
          message: '表格数据有问题，请修改数据',
          type: 'error'
        });
      }

    },
    getDepartments() {
      this.$http.get("/department")
          .then(result => {
            result = result.data;
            if (result.success) {
              this.departments = result.data;
            } else {
              this.$message({
                message: result.msg,
                type: 'error'
              });
            }
          })
          .catch(result => {
            this.$message({
              message: result.data.msg,
              type: 'error'
            });
          })
    },
    // 获取角色列表
    getRoles: function () {
      this.$http.get("/role")
          .then(result => {
            result = result.data;
            if (result.success) {
              this.roles = result.data;
            } else {
              this.$message({
                message: result.data.msg,
                type: 'error'
              });
            }
          })
          .catch(result => {
            this.$message({
              message: result.data.msg,
              type: 'error'
            });
          })
    },
    // 回显角色
    getCheckedRoles: function (id) {
      this.$http.get("/employee/roles/" + id)
          .then(result => {
            result = result.data;
            if (result.success) {
              this.$refs.tree.setCheckedKeys(result.data);
            } else {
              this.$message({
                message: result.data.msg,
                type: 'error'
              });
            }
          })
          .catch(result => {
            this.$message({
              message: result.data.data.msg,
              type: 'error'
            });
          })
    },
    // 分页事件
    handleCurrentChange(val) {
      this.employeeQuery.currentPage = val;
      this.getemployees();
    },
    handleSizeChange(val) {
      this.employeeQuery.pageSize = val;
      this.getemployees();
    },
    //获取部门列表
    getemployees() {
      this.$http.post("/employee", this.employeeQuery)
          .then(result => {
            this.pageInfo = result.data.data;
          })
          .catch(error => {
            this.$message({
              message: error.data.msg,
              type: 'error'
            });
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/employee/" + row.id)
            .then(res => {
              res = res.data
              if (res.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.listLoading = false;
                this.getemployees();
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })
            .catch(res => {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.getDepartments();
      this.saveForm = Object.assign({}, row);
      if (row.department == null) {
        this.saveForm.department = {
          id: null,
          name: ''
        }
      }
      // this.$refs['editForm'].resetFields('name');
    },
    //显示新增界面
    handleAdd: function () {

      this.saveFormVisible = true;
      this.getDepartments();
      this.saveForm = {
        id: null,
        username: '',
        password: '',
        email: '',
        headImage: '',
        age: '',
        department: {
          id: null,
          name: ''
        }
      };
      // this.$refs['editForm'].resetFields();
    },
    // 分配角色界面
    handleRole: function (index, row) {
      this.roleFormVisible = true;
      this.roleForm = Object.assign({}, row);
      // 获取角色列表
      this.getRoles();
      // 回显角色
      this.getCheckedRoles(row.id);
    },
    //编辑&新增
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            if (Object.is("",this.saveForm.department) || Object.is(null,this.saveForm.department)){
              this.saveForm.department = {
                id:null
              };
            }
            this.$http.put("/employee", this.saveForm)
                .then(res => {
                  res = res.data;
                  if (res.success) {
                    this.$message({
                      message: '提交成功',
                      type: 'success'
                    });
                    this.saveFormVisible = false;
                    this.editLoading = false;
                    this.getemployees();
                  } else {
                    this.$message({
                      message: '提交失败',
                      type: 'error'
                    });
                  }
                })
                .catch(res => {
                  this.$message({
                    message: res.data.msg,
                    type: 'error'
                  });
                });
          });
        }
      });
    },
    // 角色分配
    roleSubmit() {
      this.roleForm.roles = JSON.parse(JSON.stringify(this.$refs.tree.getCheckedNodes()));
      this.$http.put("/employee/roles", this.roleForm)
          .then(res => {
            res = res.data;
            if (res.success) {
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.roleFormVisible = false;
              this.getemployees();
            } else {
              this.$message({
                message: '提交失败',
                type: 'error'
              });
            }
          });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);

      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/employee", ids)
            .then(res => {
              res = res.data;
              if (res.success) {
                this.listLoading = false;
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.getemployees();
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })
            .catch(res => {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            });
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getemployees();
  }
}

</script>

<style scoped>

</style>